//
//  Advertiser.m
//  PANBLEPeripherialDemo
//
//  Created by 佳文 on 2018/9/26.
//  Copyright © 2018年 Panchip. All rights reserved.
//

#import "HLEAdvertiser.h"
#import "BleUtil.h"
#import <YYCategories/YYCategories.h>
#import "HLELowcostPeripherialHeader.h"
#define MAX_PAYLOAD_LEN     26

@implementation HLEAdvertiser {
    NSMutableArray* UUIDs;
    int actualPayloadLen;
    unsigned char resPayload[MAX_PAYLOAD_LEN];
}

#pragma mark - LifeCycle

+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    static HLEAdvertiser *instance = nil;
    dispatch_once(&onceToken, ^{
        instance = [[super allocWithZone:NULL] init];
        [instance initialize];
    });
    return instance;
}

#pragma mark - Public

- (void)start {
    if ([self isBluetoothEnabled] && ![self.peripheralManager isAdvertising] && UUIDs != nil) {
        [self.peripheralManager startAdvertising:
         @{
             CBAdvertisementDataServiceUUIDsKey :  UUIDs,
             CBAdvertisementDataLocalNameKey : PRO_BLUETOOTH_TAPE_LIGHT_DEFAULT_NAME_Iphone
         }];
    }
}

- (void)stop {
    if ([self.peripheralManager isAdvertising])
        NSLog(@"HLELowcostPeripherial HLEAdvertiser:\n%@\n",@"停止广播");
    [self.peripheralManager stopAdvertising];
}

- (BOOL)isAdvertising {
    return [self.peripheralManager isAdvertising];
}

- (void)setPayload:(unsigned char *)payload
{
    if (UUIDs != nil) {
        [UUIDs removeAllObjects];
    } else {
        UUIDs = [[NSMutableArray alloc] init];
    }
    NSData* data = [[NSData alloc] initWithBytes:payload length:16];
    [UUIDs addObject:[CBUUID UUIDWithData:data]];
    NSData* data1 = [[NSData alloc] initWithBytes:payload + 16 length:4];
    [UUIDs addObject:[CBUUID UUIDWithData:data1]];
}

- (void)setAddress:(Byte *)address ofLength:(int)addrLength andPayload:(unsigned char *)payload ofLength:(int)payloadLength {
    @autoreleasepool {
        actualPayloadLen = payloadLength + addrLength + PREAMBLE_LENGTH + CRC_LENGTH;
        
        get_rf_payload(address, addrLength, ADV_EXHEADER_LENGTH, payload, payloadLength, resPayload);
        
        for (int i = actualPayloadLen; i < MAX_PAYLOAD_LEN; ++i) {
            resPayload[i] = i;
        }
        
        for (int i = 0; i != MAX_PAYLOAD_LEN/2; ++i) {
            int tmp = resPayload[i*2+1];
            resPayload[i*2+1] = resPayload[i*2];
            resPayload[i*2] = tmp;
        }
        
        if (UUIDs != nil) {
            [UUIDs removeAllObjects];
        } else {
            UUIDs = [[NSMutableArray alloc] init];
        }
        
        for (int i = 0; i != 10; ++i) {
            NSData* data = [[NSData alloc] initWithBytes:resPayload+i*2 length:2];
            [UUIDs addObject:[CBUUID UUIDWithData:data]];
        }
    }
}

- (int)getAdvPayload:(Byte *)advPayload {
    if (actualPayloadLen > 0)
        memcpy(advPayload, resPayload, actualPayloadLen);
    return actualPayloadLen;
}

- (BOOL)isBluetoothEnabled {
    return self.peripheralManager.state == CBManagerStatePoweredOn;
}

#pragma mark - private

- (void)initialize {
    actualPayloadLen = -1;
    self.peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];
}

+ (id)allocWithZone:(struct _NSZone *)zone {
    return [self sharedInstance];
}


#pragma mark - Delegate
- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error {
    
}

- (void)peripheralManagerDidUpdateState:(nonnull CBPeripheralManager *)peripheral {
    
}


- (RACSubject *)advertiserSubject
{
    if (!_advertiserSubject) {
        _advertiserSubject = [RACSubject subject];
    }
    return _advertiserSubject;
}

@end


